package com.weiaibenpao.demo.chislim.ui;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.squareup.picasso.Picasso;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.bean.Li_UserBeanResult;
import com.weiaibenpao.demo.chislim.bean.UserBean;
import com.weiaibenpao.demo.chislim.hurui.activity.HBaseActivity;
import com.weiaibenpao.demo.chislim.hurui.activity.UserInfoActivity;
import com.weiaibenpao.demo.chislim.model.MyModel;
import com.weiaibenpao.demo.chislim.util.CircleImg;
import com.weiaibenpao.demo.chislim.util.CircleTransform;
import com.weiaibenpao.demo.chislim.util.Default;
import com.weiaibenpao.demo.chislim.util.FileUtil;
import com.weiaibenpao.demo.chislim.util.WriteReadSharedPrefs;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.weiaibenpao.demo.chislim.bean.UserBean.getUserBean;


public class UpdateUserActivity extends HBaseActivity {

    private TextView updateUserName;
    private TextView updateSex;
    private TextView updateHeigh;
    private TextView updateWeight;
    private TextView updateBirth;
    /*    private TextView updatePhone;
        private TextView updateEmail;*/
    private TextView okUpdate;
    private TextView userIntro;

    private ImageView myImage;
    private ImageView back;

    private Calendar cal;
    private int year;
    private int month;
    private int day;

    //用于图片的上传
    private Context context;
  //  Bitmap icon;
    private CircleImg avatarImg;// 头像图片
    //登录用户
    UserBean user;
    public static final String PREFS_NAME = "UserInfo";
    private SharedPreferences settings;
    private boolean flag=true;

    // 自定义的头像编辑弹出框
    private SelectPicPopupWindow menuWindow;
    private static final String IMAGE_FILE_NAME = "avatarImage.jpg";// 头像文件名称
    private static final int REQUESTCODE_PICK = 0;		// 相册选图标记
    private static final int REQUESTCODE_TAKE = 1;		// 相机拍照标记
    private static final int REQUESTCODE_CUTTING = 2;	// 图片裁切标记

    private String urlpath;			// 图片本地路径
    private String token;

    //--------修改用户数据后重新赋值user
    String name;

    private BottomSheetDialog mBottomSheetDialog;
    private int data;
    private String dateTime;
    private String sexSelect;
    private String months;
    private String days;
    private OkHttpClient client;

    private final static int SHANG_SUCCESS = 1;
    private Handler myHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
switch (msg.what){
    case SHANG_SUCCESS:
        dismissProgressDialog();
       String url= (String) msg.obj;
        UserBean user = getUserBean();
        user.userImage = url;
        Log.e("qiniu_url：",url);
        //展示图片
        Picasso.with(UpdateUserActivity.this)
                .load(url)
                .resize(200, 200)
                .transform(new CircleTransform())
                .error(R.mipmap.boy)
                .into(myImage);
        UpdateUserActivity.this.changeImage();
        updateUser(user.userId+"",url,"","",0,0,"","","");
        break;
}
        }
    };
    private TextView tvPhone;
    Map<String ,Object> map;
    private int num;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        context = UpdateUserActivity.this;
        setContentView(R.layout.activity_update_user);
       map=new HashMap<>();
        //注册eventBUS
        EventBus.getDefault().register(this);
        settings = getSharedPreferences(PREFS_NAME, 0);
       // icon = BitmapFactory.decodeResource(context.getResources(),R.mipmap.zhanwei);

        //获取一个日历对象
        cal = Calendar.getInstance();
        //获取年月日时分秒的信息
        year = cal.get(Calendar.YEAR);
        month = cal.get(Calendar.MONTH)+1;
        day = cal.get(Calendar.DAY_OF_MONTH);

        initdata();
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initSetData();
    }

    public void initdata() {
        user = getUserBean();
        map.put("id",user.userId);

    }

    @Override
    protected void onStart() {
        super.onStart();
        initSetData();
    }

    public void initView(){
        //new 一个BottomSheetDialog对象
        mBottomSheetDialog = new BottomSheetDialog(this);
        //完成
//        okUpdate = (TextView) findViewById(R.id.okUpdate);
//        okUpdate.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//               if (flag){
//                   updateUser();
//               }else
//                   ToastUtils.show(context,"头像上传失败");
//            }
//        });
        //用户头像
        myImage = (ImageView) findViewById(R.id.myImage);
        if(user != null && !TextUtils.isEmpty(user.userImage)){
            Picasso.with(this)
                    .load(user.userImage)
                    .resize(200, 200)
                    .placeholder(R.mipmap.boy)
                    .error(R.mipmap.boy)
                    .transform(new CircleTransform())
                    .into(myImage);
        }

        //用户昵称
        updateUserName = (TextView) findViewById(R.id.updateUserName);


        //用户性别
        updateSex = (TextView) findViewById(R.id.updateSex);
        updateSex.setText(user.userSex);

        //用户身高
        updateHeigh = (TextView) findViewById(R.id.updateHeigh);
        updateHeigh.setText(user.userHeight+"cm");

        //用户体重
        updateWeight = (TextView) findViewById(R.id.updateWeight);
        updateWeight.setText((int) user.userWeight+"kg");

        //用户生日
        updateBirth = (TextView) findViewById(R.id.updateBirth);
        updateBirth.setText(user.userBirth);




        userIntro = (TextView) findViewById(R.id.tv_signal);
        //手机号码
        tvPhone = ((TextView) findViewById(R.id.et_phone));

        tvPhone.setText(user.userPhoone);
        back = (ImageView) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    public void initSetData(){
        if (!TextUtils.isEmpty(user.userName)) {
            updateUserName.setText(user.userName);
        }
        if (!TextUtils.isEmpty(user.userTntru)) {
            userIntro.setText(user.userTntru);
        }
    }

    /**
     * 生日弹框
     * @param v
     */
    public void updateBirth(View v){

        View view = LayoutInflater.from(context).inflate(R.layout.date_layout,null,false);

       final DatePicker datePicker = (DatePicker) view.findViewById(R.id.update_datePicker);
        //初始化DatePicker组件，初始化时指定监听器

        datePicker.init(1992, 01, 01, new DatePicker.OnDateChangedListener() {
            @Override
            public void onDateChanged(DatePicker arg0, int year, int month, int day) {
                // 显示当前日期、时间
                month = month+1;
                if (month<=9 ){
                    months="0"+month;
                }else {
                    months=month+"";
                }
                if (day<=9){
                    days="0"+day;
                }else{
                    days=""+day;
                }
                dateTime = year + "-" + months + "-" + days;

                Log.i("日期",dateTime);


            }
        });
        view.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBottomSheetDialog.dismiss();
            }
        });
        view.findViewById(R.id.commit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBottomSheetDialog.dismiss();
               if (dateTime != null){
                   updateBirth.setText(dateTime);
                   user.userBirth = dateTime;
                 updateUser(user.userId+"","","","",0,0,dateTime,"","");
               }
            }
        });
        createBottomSheetDialog(view);
    }

    /**
     * 点击性别触发
     * @param v
     */
    public void updateSex(View v){
        sexDialog();
    }

    //点击身高触发
    public void userHeight(View v){
        heighDialog(2);
    }
    //点击体重触发
    public void userWeight(View v){
        heighDialog(1);
    }

    //点击个性签名触发
    public void signal_layout(View v){
        Intent intent = new Intent(this, UserInfoActivity.class);
        intent.putExtra(Default.TYPE,2);
        intent.putExtra(Default.NICK,user.userTntru);
        startActivity(intent);
//       modifyNick_address(userIntro,1);
//        userIntro.addTextChangedListener(new MaxLimitTextWatcher(userIntro,20));
    }

    //触发昵称
    public void updateName(View v){
        Intent intent = new Intent(this, UserInfoActivity.class);
        intent.putExtra(Default.TYPE,1);
        intent.putExtra(Default.NICK,user.userName);

        startActivity(intent);
//        modifyNick_address(updateUserName,2);
//        updateUserName.addTextChangedListener(new MaxLimitTextWatcher(updateUserName,10));
    }

    /**
     * 点击更换头像
     * @param v
     */
    public void updateImage(View v){

       checkPerMissions();

    }

    @Override
    public void checkPerMissions() {
        super.checkPerMissions();
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.CAMERA},1);

        }else {
            showPop();

        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            showPop();
        }
    }
  private void   showPop(){
      menuWindow = new SelectPicPopupWindow(UpdateUserActivity.this, itemsOnClick);
      menuWindow.showAtLocation(findViewById(R.id.activity_update_user),
              Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
      //发送七牛请求
      client=new OkHttpClient();
      Request request=new Request.Builder().url(Default.PRODUCT_URL + "user/uptoken") .get()
              .build();

      client.newCall(request).enqueue(new okhttp3.Callback() {
          @Override
          public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {

               token = response.body().string();
              Log.e("token", "onResponse: "+new Gson().toJson(response));
              Log.e("token", token);

          }

          @Override
          public void onFailure(okhttp3.Call call, IOException e) {
              Log.i("七牛onFailure", "error is "+e.getMessage());
          }
      });

  }
    //为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                // 拍照
                case R.id.takePhotoBtn:
                    Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    //下面这句指定调用相机拍照后的照片存储的路径
                    takeIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                            Uri.fromFile(new File(Environment.getExternalStorageDirectory(), IMAGE_FILE_NAME)));
                    startActivityForResult(takeIntent, REQUESTCODE_TAKE);
                    break;
                // 相册选择图片
                case R.id.pickPhotoBtn:
                    Intent pickIntent = new Intent(Intent.ACTION_PICK, null);
                    // 如果朋友们要限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型"
                    pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(pickIntent, REQUESTCODE_PICK);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case REQUESTCODE_PICK:// 直接从相册获取
                try {
                    startPhotoZoom(data.getData());
                } catch (NullPointerException e) {
                    e.printStackTrace();// 用户点击取消操作
                }
                break;
            case REQUESTCODE_TAKE:// 调用相机拍照
                File temp = new File(Environment.getExternalStorageDirectory() + "/" + IMAGE_FILE_NAME);
                startPhotoZoom(Uri.fromFile(temp));
                break;
            case REQUESTCODE_CUTTING:// 取得裁剪后的图片
                if (data != null) {
                    setPicToView(data);
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 裁剪图片方法实现
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, REQUESTCODE_CUTTING);
    }

    /**
     * 保存裁剪之后的图片数据
     * @param picdata
     */
    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            // 取得SDCard图片路径做显示
            Bitmap photo = extras.getParcelable("data");
            Drawable drawable = new BitmapDrawable(null, photo);
            urlpath = FileUtil.saveFile(UpdateUserActivity.this, "temphead.jpg", photo);
            uploadImageToQiniu(urlpath);
//            reg(user.userId,context,photo,"图片名称");
           /* myImage.setImageBitmap(photo);*/
            Log.i("地址",urlpath);
            /*Picasso.with(this)
                    .load("file://"+ urlpath)
                    .placeholder(R.mipmap.zw1)
                    .error(R.mipmap.zw2)
                    .transform(new CircleTransform())
                    .into(myImage);*/
        }
    }

    /**
     * 图片上传到七牛
     * @param urlpath
     */
    private void uploadImageToQiniu(String urlpath) {
        // 图片上传到七牛 重用 uploadManager。一般地，只需要创建一个 uploadManager 对象
        showProgressDialog();
        UploadManager uploadManager = new UploadManager();
        uploadManager.put(urlpath,null,token, new UpCompletionHandler() {
            @Override
            public void complete(String key, ResponseInfo info, JSONObject res) {
                try {
                    Log.e("wlx123", "res=====: "+res);
                    // 七牛返回的文件名
                    if (res != null) {
                        String upimg = res.getString("key");
                        String url=Default.PIC_URL +upimg;
                        Log.e("wlx123", "url=====: "+url );
                        Message message = myHandler.obtainMessage();
                        message.obj=url;
                        message.what=SHANG_SUCCESS;
                        myHandler.sendMessage(message);

                    }else {
                        dismissProgressDialog();
                        Toast.makeText(context,"网络",Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new UploadOptions(null, null, false,new UpProgressHandler() {
            public void progress(String key, double percent) {
                Log.e("wlx123", "percent=====: "+percent );
            }
        }, null));

    }


    //修改图片本地存放链接
    public void changeImage(){
        //获得SharedPreferences.Editor对象，使SharedPreferences对象变为可编辑状态（生成编辑器）
        SharedPreferences.Editor edit = settings.edit();
        edit.putString("userImage",user.userImage);

        //提交
        edit.commit();
    }




    /**
     * 性别弹出框
     */
    public void sexDialog(){

        final String sex[]={"男","女"};

        sexSelect=null;
       OptionsPickerView pvOptions= new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int i, int i1, int i2, View view) {
                sexSelect=sex[i];
                num=i;
                if ( sexSelect!=null) {
                    updateSex.setText(sexSelect);
                    user.userSex = sexSelect;
                    updateUser(user.userId+"","","",sexSelect,0,0,"","","");

                }else {
                    updateSex.setText(user.userSex);
                }
            }
        }).setTitleText(" ")
                .setDividerColor(Color.BLACK)
                .setOutSideCancelable(true)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setSubmitColor(Color.parseColor("#333333"))//确定按钮文字颜色
                .setCancelColor(Color.parseColor("#666666"))//取消按钮文字颜色
                .setLineSpacingMultiplier(2.0f)
                .setSelectOptions(num)
               .build();
            pvOptions.setPicker(Arrays.asList(sex));
        pvOptions.show();

    }



    /**
     * 身高或者体重弹框
     * @param style 1是体重 2是身高
     */
    public void heighDialog(final int style){

        View view = LayoutInflater.from(context).inflate(R.layout.layout_height_weight, null, false);
        final SeekBar seekBar = (SeekBar) view.findViewById(R.id.seekBar);

        TextView cancel =  view.findViewById(R.id.cancel);
        TextView commit = (TextView) view.findViewById(R.id.commit);
        final TextView allWeight = (TextView) view.findViewById(R.id.allWeight);
           if (style==1){
               seekBar.setMax(150);
               allWeight.setText((int) user.userWeight + "kg");
               seekBar.setProgress((int) user.userWeight);
           }
           if (style==2){
               seekBar.setMax(230);
               allWeight.setText(Math.round(user.userHeight) + "cm");
               seekBar.setProgress(user.userHeight);
           }
        Log.e("wlc33", "user.userHeight: "+user.userHeight );


        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mBottomSheetDialog.dismiss();
            }
        });
        commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                mBottomSheetDialog.dismiss();
                if (style == 1) {
                    user.userWeight=data;
                    updateWeight.setText(data+"kg");
                    updateUser(user.userId+"","","","",0,data,"","","");

                } else if (style == 2) {
                    user.userHeight=  data;
                    updateHeigh.setText(data+"cm");
                    updateUser(user.userId+"","","","",data,0,dateTime,"","");
                }

            }
        });

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                    data=i;
                if (style == 1) {
                    allWeight.setText(i+"kg");
                } else if (style == 2) {
                    allWeight.setText(i+"cm");
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        createBottomSheetDialog(view);
    }



    /**
     * 底部滑动显示
     *
     */
    private void createBottomSheetDialog(View view) {

        mBottomSheetDialog.setContentView(view);
        //显示
        mBottomSheetDialog.show();
    }

    /**
     * 修改用户信息
     */
    public void updateUser(String id,String userImage,String userName,String userSex,int userHeigh,float userWeight,
                           String userBirth,String userPhone,String userIntru){

        Call<Li_UserBeanResult> call = MyModel.getModel().getService().updateUserInfo(id,userImage,userSex,userName,userHeigh,userWeight,
                userBirth,userPhone,userIntru);

        call.enqueue(new Callback<Li_UserBeanResult>() {
            @Override
            public void onResponse(Call<Li_UserBeanResult> call, Response<Li_UserBeanResult> response) {
                if (response.isSuccessful()) {
                    Li_UserBeanResult result = response.body();
                    Log.e("", "onResponse: "+new Gson().toJson(response) );
                    if (result.getCode() == 0) {
                        Toast.makeText(context,"修改成功",Toast.LENGTH_SHORT).show();
                        WriteReadSharedPrefs.writeUser(context,result.getData());
                        WriteReadSharedPrefs.readUser(context, getUserBean());
                        EventBus.getDefault().post(true);

                    }
                }else{
                    Toast.makeText(context,"fail",Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onFailure(Call<Li_UserBeanResult> call, Throwable t) {
                Toast.makeText(context,t.getMessage(),Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Subscribe
    public void onMessageEvent(String str) {
        updateUserName.setText(str);

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
